package net.zjitc.security.auth;

import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Component;

import java.util.Collection;

@Component
public class MyAccessDecisionManager implements AccessDecisionManager {
    /**
     *
     * @param authentication 用户所具有权限
     * @param object
     * @param configAttributes 访问资源时应该有的权限
     * @throws AccessDeniedException
     * @throws InsufficientAuthenticationException
     */
    @Override
    public void decide(Authentication authentication, Object object, Collection<ConfigAttribute> configAttributes) throws AccessDeniedException, InsufficientAuthenticationException {
        //无需验证放行
        if (configAttributes == null || configAttributes.size() == 0
                || authentication.getAuthorities()==null || authentication.getAuthorities().size()==0)
            return;

        if (!authentication.isAuthenticated()) {
            throw new InsufficientAuthenticationException("未登录");
        }
        //
        Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
        //权限的比较
        for (ConfigAttribute attribute : configAttributes) {//url对应的权限
            MyConfigAttribute urlConfigAttribute = (MyConfigAttribute) attribute;
            for (GrantedAuthority authority : authorities) { //用户的权限
                String userAuthority = authority.getAuthority();
                if (urlConfigAttribute.getMyGrantedAuthority().getPid().equals(userAuthority))
                    return;
            }
        }
        throw new AccessDeniedException("无权限");
    }

    @Override
    public boolean supports(ConfigAttribute attribute) {
        return true;
    }

    @Override
    public boolean supports(Class<?> clazz) {
        return true;
    }
}
